﻿using System;
using System.Windows.Forms;
using Microsoft.VisualStudio.TestTools.WebTesting;

namespace ViewstatePlaybackAddin
{
    public partial class WebTestViewStateUserControl : UserControl
    {
        public WebTestViewStateUserControl(WebTestResultDetails resultDetails)
        {
            InitializeComponent();
            UpdateSummaryDetails(resultDetails);
        }

        public void UpdateSummaryDetails(WebTestResultDetails resultDetails)
        {
            string currentViewstate = String.Empty;
            foreach (WebTestResultIteration resultIteration in resultDetails.WebTestIterations)
            {
                int pageNumber = 0;
                foreach (WebTestResultUnit resultItem in resultIteration.Children)
                {
                    WebTestResultPage pageResult = resultItem as WebTestResultPage;
                    if (pageResult != null)
                    {
                        pageNumber++;
                        currentViewstate = GetFormFieldValue(pageResult.RequestResult.Response, "__VIEWSTATE", 0);
                        int length = (null == currentViewstate) ? 0 : currentViewstate.Length;

                        ListViewItem item = new ListViewItem(new string[] { pageNumber.ToString(), length.ToString(), pageResult.RequestResult.Request.Url });
                        ViewStatesListView.Items.Add(item);
                    }
                }
            }
        }

        public void UpdateSelectionDetails(WebTestRequestResult result)
        {
            string viewstate = GetFormFieldValue(result.Response, "__VIEWSTATE", 0);
            CurrentViewstateSizeLabel.Text = "Selected Request Viewstate Size:  "+((viewstate == null) ? "0" : viewstate.Length.ToString());
        }

        private string GetFormFieldValue(WebTestResponse response, string formFieldName, int index)
        {
            int count = 0;

            foreach (HtmlTag tag in response.HtmlDocument.HtmlTags)
            {
                if (String.Equals(tag.GetAttributeValueAsString("name"), formFieldName, StringComparison.OrdinalIgnoreCase)
                        || String.Equals(tag.GetAttributeValueAsString("id"), formFieldName, StringComparison.OrdinalIgnoreCase))
                {
                    if (index == -1 || count++ == index)
                    {
                        string formFieldValue = tag.GetAttributeValueAsString("value");
                        if (formFieldValue == null)
                        {
                            formFieldValue = String.Empty;
                        }

                        return formFieldValue;
                    }
                }
            }

            return null;
        }
    }
}
